package zheezes.protocol.impl.gd;

import zheezes.protocol.Frame;
import zheezes.protocol.PacketAnalyzer;
import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;

public class GdPacketAnalyzer extends PacketAnalyzer {
	@Override
	public int[] checkPacket(byte[] buf, int length) {
		int idx = 0;
		int len = length;
		int dataLen;// L
		byte chksum = 0x00;// cs

		while ((idx = ArrayUtil.find(buf, idx, len, (byte) 0x68)) >= 0) {
			len = len - idx;
			if (len >= 8 + 1 + 2 + 2) {
				if (buf[idx + 7] == 0x68) {
					dataLen = ByteUtil.ctos(buf, idx + 9);
					chksum = (byte) ArrayUtil.sum(buf, idx, dataLen + 11);
					if ((buf[dataLen + 11] == chksum)
							&& (buf[dataLen + 12] == 0x16)) {
						return new int[] { idx, dataLen + 13 };
					}
				}
			} else {// not enough length
				return new int[] { idx, -1 };
			}
		}
		// don't have a valid frame header
		return new int[] { length, -1 };
	}

	@Override
	public Frame parse(byte[] buf, int length) {
		return GdFrame.getFrame(buf, 0, length);
	}
}
